package com.mnt.washio.utils.network.ws;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;

import com.mnt.washio.objects.OrderObject;
import com.mnt.washio.utils.Statics;
import com.mnt.washio.utils.network.NetworkUtils;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;

@SuppressLint("SimpleDateFormat")
public class GetCurrentOrderWSControl extends BaseWSControl {
	private String idUser;

	public GetCurrentOrderWSControl(Context context,
			WebServiceCommunicatorListener listener, String idUser) {
		super(context, listener, WebServiceFlag.ORDER_CURRENT);
		this.idUser = idUser;
	}

	@Override
	protected Object doInBackground(Void... params) {
		// Get local database
		String url = Statics.ADMIN_WS_URL + "orders/current/byuser/" + idUser;

		try {
			String respone = NetworkUtils.doRequest(url);
			try {
				JSONObject jsonObject = new JSONObject(respone);

				return getCurrentOrder(jsonObject);
			} catch (JSONException e) {
				mError = e.getMessage();
			}

		} catch (ClientProtocolException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		} catch (IOException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		}
		return null;
	}

	public OrderObject getCurrentOrder(JSONObject jsonObject){
		OrderObject order = new OrderObject();
		try {
			order.setOrderId(Statics.getString(jsonObject, "id"));
			order.setPickupDate(Statics.getString(jsonObject, "pickup"));
			order.setPickupTime(Statics.getString(jsonObject, "pickupTime"));
			order.setDropoffDate(Statics.getString(jsonObject, "dropoff"));
			order.setDropoffTime(Statics.getString(jsonObject, "dropoffTime"));
			order.setRating(Statics.getString(jsonObject, "rating"));
			
			JSONObject jsonObjStatus = jsonObject.getJSONObject("status");
			order.setStatusClient(Statics.getString(jsonObjStatus, "statusClient"));
			order.setStatusLookup(Statics.getString(jsonObjStatus, "statusLookup"));
			order.setOrdinalValueClient(Statics.getInt(jsonObjStatus, "ordinalValueClient"));
			
			JSONObject pickupShiftActual = Statics.getJSONObject(jsonObject, "pickupShiftActual");
			JSONObject user = Statics.getJSONObject(pickupShiftActual, "user");
			order.setUrlImgPick(Statics.getString(user, "profileUrl"));
			
			JSONObject dropoffShiftActual = Statics.getJSONObject(jsonObject, "dropoffShiftActual");
			JSONObject user1 =Statics.getJSONObject(dropoffShiftActual, "user");
			order.setUrlImgDrop(Statics.getString(user1, "profileUrl"));
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			return null;
		}
		
		
		
		
		return order;
	}
	
}
